import { fileURLToPath, URL } from 'node:url'

import { defineConfig,loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'

// https://vitejs.dev/config/
export default defineConfig(({mode})=>{
  
  const env = loadEnv(mode,process.cwd(),'')
  return {
    base: env.VITE_PUBLIC_PATH,
    plugins: [
      vue(),
      AutoImport({
        resolvers: [ElementPlusResolver()],
      }),
      Components({
        resolvers: [ElementPlusResolver()],
      }),
    ],
    
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url))
      }
    },
    server: {
      host: true,
      // 仅在 proxy 中配置的代理前缀， mock-dev-server 才会拦截并 mock
      // doc: https://github.com/pengzhanbo/vite-plugin-mock-dev-server
      proxy: {
        "/dev-api": {
          target: "",
          changeOrigin: true,
          rewrite: path => path.replace(/^\/dev-api/, ''),
          secure: false,
          configure: (proxy, options) => {
            // 配置此项可在响应头中看到请求的真实地址
            proxy.on('proxyRes', (proxyRes, req) => {
              proxyRes.headers['x-real-url'] = new URL(req.url || '', options.target)?.href || ''
            })
          }
        }
      }
    },
    build: {
      outDir: "web",      // 默认dist（可省略），打包后输出文件
      assetsDir: "assets", // 默认assets（可省略），指定静态资源存放路径
      sourcemap: false,    // 默认false（可省略），是否构建sourcemap文件（生产不需要）
  
      terserOptions: {
        // 生产环境移除console、debugger
        compress: {
          drop_console: true,   // 默认false
          drop_debugger: true,  // 默认true
        },
      },
  
      rollupOptions: {
        output: {
          chunkFileNames: "static/js/[name]-[hash].js",
          entryFileNames: "static/js/[name]-[hash].js",
          assetFileNames: "static/[ext]/[name]-[hash].[ext]"
        }
      }
    }
  
  }
})
